import { createHandle, isShallowEqual, createRandomString } from './utils'

const componentConfig = {
  properties: {
    data: {
      type: Object,
    },
  },
  data: {
    type: '',
    props: {},
    children: null,
    content: '',
    pageId: '',
    nodeId: '',
  },
  observers: {
    data(data) {
      if (!data) {
        return
      }

      const { type, props, children } = this.data
      if (type !== data.type) {
        const { type, props = {}, children = null, content = '' } = data
        this.setData({ type, props, children, content })
      }
      else {
        const next = {}
        let flag = false

        if (!isShallowEqual(props, data.props)) {
          next.props = data.props || {}
          flag = true
        }

        if (!isShallowEqual(children, data.children)) {
          next.children = data.children
          flag = true
        }

        if (flag) {
          this.setData(next)
        }
      }
    },
  },
  lifetimes: {
    attached() {
      if (!this.properties.data) {
        return
      }
      const { type, props = {}, children = [], content = '' } = this.properties.data
      const pageId = this.getPageId()
      const nodeId = this.nodeId || createRandomString(16)
      this.nodeId = nodeId
      this.setData({ type, props, children, pageId, nodeId, content })
    },
  },
  methods: {},
}

// createHandlers
{
  const handlers = [
    'onTouchStart',
    'onTouchMove',
    'onTouchEnd',
    'onTouchCancel',
    'onTap',
    'onLongPress',
    'onCoverImageLoad',
    'onCoverImageError',
    'onButtonGetUserInfo',
    'onButtonContact',
    'onButtonGetPhoneNumber',
    'onButtonError',
    'onButtonOpenSetting',
    'onButtonLaunchApp',
    'onButtonGetRealnameAuthInfo',
  ]
  handlers.forEach((name) => {
    componentConfig.methods[name] = createHandle(name)
  })
}

Component(componentConfig)
